//auto function
$(function() {
	// predefine the pop-up window
    $( "#detailBox" ).dialog({
        modal: false,
        autoOpen: false,
        minHeight: 280,
        minWidth:530,
        width: 600,
        open: function(event, ui) {
            $(event.target).parent().css('top', '5px');
            $(event.target).parent().css('left', '10px');
        }
    });
    // event handler when the pop-up window is resized
    $('#detailBox').bind("dialogresize", function (event, ui) {
    	reSizedetailBox();
    });
});

//current id of detail table
var tableId ='';
var currButtonId ='';
var currUseMapId = '';
var buttonFocusClass = 'popup-table-button-focus';
var buttonSelectedClass = 'popup-table-button-selected';
var popupTableButtonClass = 'popup-table-button';
var popupTableFooterText = 'popup-table-footer-text';
//collect client conditions and push to server to retrieving excel file
function exportToExcel(imgId)
{	
	var img = new String(imgId);
	var params = 'priority='			+img.charAt(1)
				+'&prodArea='			+img.charAt(3)
				+'&partId='				+$("#hiddenPartId").val()
				+'&selectedStage='		+$("#hiddenStage").val()
				+'&selectedLocation='	+$("#hiddenLocation").val()
				+'&selectedEqptype='	+$("#hiddenEqpType").val()
				+'&equipId='			+$("#hiddenEqpId").val()
				+'&selectedYear='		+$("#hiddenYear").val()
				+'&customerName='		+$("#hiddenCustomerName").val()
				;
	download('exportDiagramExcel.do',params);
}

function loadGraph()
{
	document.searchForm.submit();
}

function zoomInAllMap()
{
	var i=0;
	for (i=0 ;i<document.images.length;++i)
		{
			if (document.images[i].id.charAt(0) == 'P' && document.images[i].id.charAt(2) == 'F')
				{
					zoomMapFirstTime(document.images[i].id);
				}
		}
}

// handler function was called when user click on a chart point
function chartPointClicked(obj,caption,caption1)
{
	//collect chart point info
	var chartInfo = getSelectedChartInfo(obj,caption,caption1);
	//create table if selected point is not fx factor
	if (chartInfo.type.search('F')<0)
		{
			//	create new table id
			var newPossibleTable = chartInfo.type+chartInfo.month+chartInfo.priority+chartInfo.prodArea;
			while (newPossibleTable.search(' ')>-1)
			{
				newPossibleTable = newPossibleTable.replace(' ','');
			}
			var isDetailBoxVisible = $('#detailBox').dialog( "isOpen" );
			// if new table has different id with the current table
			if (!(tableId.match(newPossibleTable) && tableId.length == newPossibleTable.length && isDetailBoxVisible))
			{
				//unload grid
				unloadCurrentTable();
				//set id for current table
				tableId = newPossibleTable;
				//calculate new information for detail table
				var conditions = createTableInfo(chartInfo);
				//open dialog
				openDialog(chartInfo.caption1, chartInfo.title, conditions.pager);
				//create table
				createdetailBox(conditions);
			}
		}
	else
		{
			//open dialog
			unloadCurrentTable();
			openDialog(chartInfo.caption1, chartInfo.title, '');
			emptyTableMessage();
		}
	// selected current conditions
	selectCurrentCondition(chartInfo.month);
}

function createTableInfo(info)
{
	var pagerId = tableId+'Pager';
	var conditions = {
							priority : info.priority, prodArea : info.prodArea, partId : $("#hiddenPartId").val(),
							selectedStage: $("#hiddenStage").val(), selectedLocation : $("#hiddenLocation").val(),
							selectedEqptype: $("#hiddenEqpType").val(), equipId: $("#hiddenEqpId").val(),
							selectedYear: $("#hiddenYear").val(),customerName:$("#hiddenCustomerName").val(),
							month:info.month, type:info.type, tableId : tableId, pager: pagerId
					 };
	return conditions;
}
function getSelectedChartInfo(obj,caption,caption1)
{
	//get chart title
	caption = caption.replace('(','').replace(')','');
	caption1 = caption1.replace('(','').replace(')','');
	var caps = caption.split(',');
	var type = caps[0];
	currButtonId = type+"Button";
	caps = caps[1].split('=');
	var month  = caps[0].substring(1,5).replace(' ','');
	
	//get chart name
	var useMapName = obj.parentNode.name;
	currUseMapId = useMapName;
	//find chart priority and prodarea
	var i=0;
	var priority ='0';
	var prodArea ='0';
	for (i=0 ;i<document.images.length;++i)
	{
		if (document.images[i].id.charAt(0) == 'P' && document.images[i].id.charAt(2) == 'F')
			{
				var chart = document.images[i];
				var useMap = chart.getAttribute("usemap");
				useMap = useMap.replace("#", "");
				if (useMap.match(useMapName)&&useMap.length==useMapName.length)
					{
						priority = document.images[i].id.charAt(1);
						prodArea = document.images[i].id.charAt(3);
						break;
					}
			}
	}
	// box title
	var prodAreaTitle = '';
	if (prodArea == 1)
		{
			prodAreaTitle = 'FAB1'; 
		}
	else if (prodArea == 2)
		{
			prodAreaTitle = 'FAB2'; 
		}
	else if (prodArea == 3)
		{
			prodAreaTitle = 'FAB1&FAB2'; 
		}
	var title = 'Priority : '+priority + ' - ProdArea : '+ prodAreaTitle;
	return {priority : priority, prodArea : prodArea,title:title, month : month,type:type,caption1:caption1};
}
function openDialog(caption1, title, pagerId)
{
	$("#detailBox").dialog("open");
	$("#detailBox").dialog('option', 'title', title);
	$("#detailBox" ).html('');
	$("#detailBox" ).append('<div id="detailBoxHeader" class="popup-table-header"></div><div align="center" style="height:200px;"><table id="'+tableId+'"></table><div id="'+pagerId+'"></div><div id="detailBoxFooter" class="popup-table-footer"></div></div>');
	$("#detailBoxHeader").html('<table id="detailBoxCondition">' +
									'<tr>'+
										'<td id="detailBoxPointInfo" width="30%">'+caption1+'</td>' +
										'<td width="70%" align="right" nowrap="nowrap">'+
											'<select id="detailBoxMonth" class="popup-table-selection-box">'+
												'<option label="'+($("#hiddenYear").val()-1)+'" value="'+($("#hiddenYear").val()-1)+'" selected="selected">'+($("#hiddenYear").val()-1)+'</option>'+
												'<option label="Jan" value="Jan" selected="selected">Jan</option>'+
												'<option label="Feb" value="Feb">Feb</option>'+
												'<option label="Mar" value="Mar">Mar</option>'+
												'<option label="Apr" value="Apr">Apr</option>'+
												'<option label="May" value="May">May</option>'+
												'<option label="Jun" value="Jun">Jun</option>'+
												'<option label="Jul" value="Jul">Jul</option>'+
												'<option label="Aug" value="Aug">Aug</option>'+
												'<option label="Sep" value="Sep">Sep</option>'+
												'<option label="Oct" value="Oct">Oct</option>'+
												'<option label="Nov" value="Nov">Nov</option>'+
												'<option label="Dec" value="Dec">Dec</option>'+
											'</select>'+
											'<span id="X-PlanButton" class="'+popupTableButtonClass+'">X-Plan</span>'+
											'<span id="X-RWButton" class="'+popupTableButtonClass+'">X-RW</span>'+
											'<span id="X-RWHButton" class="'+popupTableButtonClass+'">X-RWH</span>'+
											'<span id="F-X-PlanButton" class="'+popupTableButtonClass+'">FX-Plan</span>'+
											'<span id="F-X-RWButton" class="'+popupTableButtonClass+'">FX-RW</span>'+
											'<span id="F-X-RWHButton" class="'+popupTableButtonClass+'">FX-RWH</span>'+
										'</td>'+
									'</tr>'+
								 '</table>');
	//positioning buttons
	formatButtonGroup();
	//event handler on popup-button
	$("."+popupTableButtonClass).hover(function() {
		if (!(this.id.match(currButtonId) && this.id.length == currButtonId.length ))
			{
				$(this).addClass(buttonFocusClass);
			}
	}, function(id) {
		if (!(this.id.match(currButtonId) && this.id.length == currButtonId.length ))
			{
				$(this).removeClass(buttonFocusClass);
			}
	});
	$("."+popupTableButtonClass).click(function()
			{
				var buttonId = this.id;
				if (!(buttonId.match(currButtonId)&& buttonId.length == currButtonId.length))
					{
						//changed selected button
						$("#"+currButtonId).removeClass(buttonSelectedClass);
						$("#"+currButtonId).removeClass(buttonFocusClass);
						var selectedMonth =  $("#detailBoxMonth").val();
						findValuePoint(buttonId,selectedMonth);
					}
			});
	$("#detailBoxMonth").change(function()
			{
				var selectedMonth =  $("#detailBoxMonth").val();
				findValuePoint(currButtonId,selectedMonth);
			});
}

function findValuePoint(buttonId, selectedMonth)
{
	var map = document.getElementById(currUseMapId);
	var pointType = buttonId.replace("Button","");
	var valuePoint = null;
	if (map != null)
	{
	    for (var i = 0; i < map.areas.length; i++) {
	      var area = map.areas[i];
	      for (var j = 0; j< area.attributes.length; j++)
	    	  {
	    	  	 var attName = area.attributes[j].name;
	    	  	 if (attName.match('onclick'))
	    	  		 {
	    	  		 	var browser = navigator.appName;
	    	  		 	var text ='';
	    	  		 	if (browser.match('Microsoft Internet Explorer'))
	    	  			   {
	    	  		 		   text = area.attributes[j].value; 	
	    	  			   }
	    	  		 	else
	    	  		 		{
	    	  		 			text = area.attributes[j].firstChild.data;
	    	  		 		}
	    	  		 	var pointText = "("+pointType+",";
	    	  		 	if (text.indexOf(pointText)>=0 && text.match(selectedMonth))
	    	  		 		{
	    	  		 			valuePoint=area;
	    	  		 			break;
	    	  		 		}
	    	  		 }
	    	  }
	      if (valuePoint != null)
	    	  {
 	  		 	break;
	    	  }
	    }
	}
	if (valuePoint != null)
	{
	    if( document.createEvent ) {
	    	var e = document.createEvent('MouseEvents');
		    e.initEvent( 'click', true, true );
		    valuePoint.dispatchEvent(e);

	      } else if( document.createEventObject ) {
	        var e = document.createEventObject();
	        valuePoint.fireEvent( 'onclick', e );
	      }
	}
	else
	{
		unselectCurrentButton();
		$("#detailBoxPointInfo").html('No Value!');
		currButtonId = buttonId;
		//unload grid
		unloadCurrentTable();
		emptyTableMessage();
		selectCurrentCondition(selectedMonth);
	}
}
function selectCurrentCondition(month)
{
	$("#"+currButtonId).addClass(buttonSelectedClass);
	$("#detailBoxMonth").val(month);
}

function createdetailBox(conditions)
{
	if (conditions.type.match('X-RWH'))
		{
			populateXRWH(conditions);
			jQuery("#detailBoxFooter").html('<span class="'+popupTableFooterText+'">Top 50 recipes with highest Hold Duration values</span>');
		}
	else if (conditions.type.match('X-RW'))
		{
			populateXRW(conditions);
			jQuery("#detailBoxFooter").html('<span class="'+popupTableFooterText+'">Top 50 recipes with highest X-RW values</span>');
		}
	else
		 if (conditions.type.match('X-Plan'))
		{
			populateXPlan(conditions);
			jQuery("#detailBoxFooter").html('<span class="'+popupTableFooterText+'">Top 50 recipes with highest X-Plan values</span>');
		}
}

function populateXFactor(conditions, xFactor) {
	
	jQuery("#"+conditions.tableId).jqGrid({
		url: 'loadXFactorDetailTable.do',
		datatype: "json",
	   	colNames:xFactor.colNames,
	   	colModel:xFactor.colModel,
	   	postData : conditions,
	   	rowNum:50,
//	    height: 350,
	    width: 600,
	    shrinkToFit: true,
	    headertitles : true,
	    rownumbers : true,
	    loadonce: true,
	    emptyrecords: 'No Records found',
	    gridview : true,
		scrolling: true,
		autowidth: true,
//	   	rowList:[15,20,30],
	   	pager: conditions.pager,
	    viewrecords: true
	});
	reSizedetailBox();
};

function reSizedetailBox()
{
	$("#"+tableId).jqGrid('setGridWidth', $("#detailBox" ).width() - 20);
	$("#"+tableId).jqGrid('setGridHeight', $("#detailBox" ).height() - 115);
	formatButtonGroup();
}

function populateXRWH(conditions)
{
	populateXFactor(conditions,{
		colNames: [ 
		            'LotId','PartId',conditions.type,
					'TimeRev','Recipe','Hold Duration',
					'Hold Code','Hold Comment','Release Comment',
					'Customer Name','Area',
					'Location','Stage','EqpType'
				  ],
		colModel: [
					{
	   					name : 'LotId',index : 'LotId',width : 60,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'PartId',index : 'PartId',width : 100,editable:false,sorttable: false
	   				},
	   				{
	   					name : conditions.type,index : conditions.type,width : 40,align: "right", sorttype: "float", editable:false,sorttable: false
	   				},
	   				{
	   					name : 'TimeRev',index : 'TimeRev',width : 140,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Recipe',index : 'Recipe',width : 70,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Hold Duration',index : 'Hold Duration',width : 80,align: "right", sorttype: "float",editable:false,sorttable: true
	   				},
	   				{
	   					name : 'Hold Code',index : 'Hold Code',width : 60,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Hold Comment',index : 'Hold Comment',width : 100,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Release Comment',index : 'Release Comment',width : 120,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Customer Name',index : 'Customer Name',width : 120,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Area',index : 'Area',width : 40,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Location',index : 'Location',width : 70,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Stage',index : 'Stage',width : 80,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'EqpType',index : 'EqpType',width : 70,editable:false,sorttable: false
	   				}
	   						
	   			]
	}
	);
}

function populateXRW(conditions)
{
	populateXFactor(conditions,{
		colNames: [ 
		            'LotId','PartId',conditions.type,
					'TimeRev','Recipe','Area',
					'Location','Stage','EqpType'
				  ],
		colModel: [
					{
	   					name : 'LotId',index : 'LotId',width : 60,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'PartId',index : 'PartId',width : 100,editable:false,sorttable: false
	   				},
	   				{
	   					name : conditions.type,index : conditions.type,width : 40,align: "right", sorttype: "float",editable:false,sorttable: true
	   				},
	   				{
	   					name : 'TimeRev',index : 'TimeRev',width : 140,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Recipe',index : 'Recipe',width : 70,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Area',index : 'Area',width : 40,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Location',index : 'Location',width : 80,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Stage',index : 'Stage',width : 80,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'EqpType',index : 'EqpType',width : 80,editable:false,sorttable: false
	   				}
	   						
	   			]
	}
	);
}

function populateXPlan(conditions)
{
	populateXFactor(conditions,{
		colNames: [ 
		            'LotId','PartId',conditions.type,
					'Recipe','Area',
					'Location','Stage','EqpType'
				  ],
		colModel: [
					{
	   					name : 'LotId',index : 'LotId',width : 60,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'PartId',index : 'PartId',width : 100,editable:false,sorttable: false
	   				},
	   				{
	   					name : conditions.type,index : conditions.type,width : 40,align: "right", sorttype: "float",editable:false,sorttable: true
	   				},
	   				{
	   					name : 'Recipe',index : 'Recipe',width : 70,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Area',index : 'Area',width : 40,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Location',index : 'Location',width : 80,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'Stage',index : 'Stage',width : 80,editable:false,sorttable: false
	   				},
	   				{
	   					name : 'EqpType',index : 'EqpType',width : 80,editable:false,sorttable: false
	   				}
	   						
	   			]
	}
	);
}

function formatButtonGroup()
{
	$("#detailBoxCondition").width($("#detailBox" ).width() - 30);
}

function emptyTableMessage()
{
	jQuery("#detailBoxFooter").html('<span class="'+popupTableFooterText+'">No record found for this type!</span>');
}

function unloadCurrentTable()
{
	if (tableId.length>0)
	{
		jQuery("#"+tableId).jqGrid('GridUnload');
	}
	tableId='';
}

function unselectCurrentButton()
{
	//changed selected button
	$("#"+currButtonId).removeClass(buttonSelectedClass);
	$("#"+currButtonId).removeClass(buttonFocusClass);
}